from rest_framework.views import exception_handler as exception_handler_raw


def get_dict_or_list_str(data):
    if not isinstance(data, (dict, list)):
        return data
    elif isinstance(data, dict):
        return [val for key, val in data.items()][0]
    else:
        return data[0]


def validation_error_to_str(data):
    if hasattr(data, 'general'):
        error_detail = data['general']
    else:
        error_detail = [val for key, val in data.items()][0]
    return get_dict_or_list_str(error_detail)


def exception_handler(exc, context):

    # Call REST framework's default exception handler first,
    # to get the standard error response.
    response = exception_handler_raw(exc, context)
    if not response:
        return None
    _data = response.data
    code = response.status_code
    message = validation_error_to_str(_data)
    data = _data
    response.data = {
        'code': code,
        'message': message,
        'data': data
    }
    return response
